package com.linetime.wechat.util;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Status;
import com.linetime.core.utils.JacksonUtil;
import com.linetime.core.utils.StringUtil;
import com.linetime.wechat.constants.WechatAPI;
import com.linetime.wechat.exception.WechatException;
import com.linetime.wechat.response.GetAccessTokenResponse;

import java.util.Objects;

/**
 * @author sangaizhi
 * @date 2018/9/23
 */
@SuppressWarnings(value = "unchecked")
public class WechatHelper {

    /**
     * 获取 Access token
     *
     * @param appId     公众号的 appId
     * @param appSecret 公众号的 appSecret
     * @return token 信息
     */
    public static GetAccessTokenResponse getAccessToken(String appId, String appSecret) {
        if (StringUtil.isBlank(appId)) {
            throw new WechatException("App id is empty");
        }
        if (StringUtil.isBlank(appSecret)) {
            throw new WechatException("App secret is empty");
        }
        String url = WechatAPI.ACCESS_TOKEN_GET_API.replace("APP_ID", appId).replace("APP_SECRET", appId);
        HttpResponse response = HttpRequest.get(url).execute();
        if (null == response) {
            throw new WechatException("Get access token failure,response from the wechat is empty");
        }
        if (!Objects.equals(response.getStatus(), Status.HTTP_OK)) {
            throw new WechatException("Get access token failure,the response status from wechat is {}", response.getStatus());
        }
        String responseBody = response.body();
        if (StrUtil.isBlank(responseBody)) {
            throw new WechatException("The response body from the wechat is empty");
        }
        return JacksonUtil.toBean(responseBody, GetAccessTokenResponse.class);
    }

}
